package com.apes.scm.rbac.repository;

import com.apes.framework.jpa.repository.CustomRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.rbac.model.LocalPermit;
import com.apes.scm.rbac.model.LocalPermitItem;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Date;
import java.util.List;

public interface LocalPermitRepository extends CustomRepository<LocalPermit, String> {
    @Query("select T from LocalPermit T where lastUpdatedStamp > :times or (id > :id and lastUpdatedStamp = :times) order by lastUpdatedStamp, id asc ")
    List<LocalPermit> findByLastUpdatedStampAndId(@Param("times") Date times, @Param("id") String id, Pageable pageable);

    @Query(value = "select t.* from aut_local_permit t  left join aut_local_permit_item a on t.id = a.local_permit_id " +
            " where a.type = 'pt_supplier' and a.org_id = :supplierId and a.purpose = 'pp_belong'" +
            " and exists (select 1 from aut_local_permit_item c where c.local_permit_id  = t.id" +
            "           and c.type = 'pt_company' and c.org_id = :companyId" +
            "           and  c.purpose = 'pp_belong')" , nativeQuery = true)
    List<LocalPermit> findByTypeAndOrgId(@Param("supplierId") String supplierId, @Param("companyId") String companyId);

    @Query("select T from LocalPermit T where 1 = 1 and T.id = :id")
    LocalPermit findLocalPermit(@Param("id") String id);

    @Modifying
    @Query(value = "delete from aut_local_permit_item T where T.ORG_ID = :orgId and T.PURPOSE = :purpose and T.TYPE = :theType and T.LOCAL_PERMIT_ID = :id",nativeQuery = true)
    void deleteLocalPermitItem(@Param("orgId") String orgId, @Param("purpose") Enumeration purpose, @Param("theType") Enumeration type,@Param("id") String id);

    @Query("select T from LocalPermitItem T where T.type = 'pt_dept' and T.id = :id")
    List<LocalPermitItem> findByType(@Param("id") String id);
}
